
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Xml.Linq;
using Microsoft.AspNetCore.Mvc;
using ST.Core;
using ST.Data;
using ST.ModelVM;
using ST.ModelVM.ProtocolDefine;
using ST.ModelVM.ProtocolSimHost;
using ST.ModelVM.ProtocolSimLog;
 

namespace ST.Simulator.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProtocolSimLogController : ControllerBase
    {
         
        IRepository<Data.ProtocolSimLog> _IRepository ;

        IRepository<Data.ProtocolSimHost> _IRepositoryProtocolSimHost;

        public ProtocolSimLogController(IRepository<Data.ProtocolSimLog> repository1 , IRepository<Data.ProtocolSimHost>  r2)
        {
           
            _IRepository = repository1;
            _IRepositoryProtocolSimHost= r2;


        }   
        
        [HttpPost("Page")]
        public PageResult<ProtocolSimLog> Page(ProtocolSimLogQM qm){
            var q = _IRepository.GetAll();
            if (qm.ProtocolSimId != 0)
            {
                q=q.Where(a=>a.ProtocolSimId == qm.ProtocolSimId);  
            }
            if(qm.ProtocolSimHostId != 0)
            {
                q=q.Where(a=>a.ProtocolSimHostId == qm.ProtocolSimHostId);
            }
            if (qm.Dtb.HasValue )
            {
                q = q.Where(a => a.Dt>=qm.Dtb.Value);
            }
            if (qm.Dte.HasValue)
            {
                q = q.Where(a => a.Dt <= qm.Dte.Value);
            }
            if (!string.IsNullOrEmpty(qm.Key))
            {
                q = q.Where(a => a.Memo.Contains(qm.Key)||a.Data.Contains(qm.Key) );
            }

            var lsimhost = _IRepositoryProtocolSimHost.GetAll().ToList();
            var r=new PageResult<ProtocolSimLog>(); 
            r.Total= q.Count();
            r.Data=q
                .OrderByDescending(a=>a.Id)
                .Skip( (qm.Page-1)*qm.PageSize)
                .Take(qm.PageSize)
                .ToList();
            foreach (var item in r.Data)
            {
                try {
                    if (item.ProtocolSimHostId > 0)
                    {
                        item.ProtocolSimHostName = lsimhost.Where(a => a.Id == item.ProtocolSimHostId).FirstOrDefault().HostName;
                    }
                    
                }
                catch { }
                
            }
            return r;
        }
         

    }
}